package com.bawei.module_main


import android.Manifest
import android.animation.ValueAnimator
import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.view.animation.LinearInterpolator
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.alibaba.android.arouter.facade.annotation.Route
import com.bawei.module_home.home.HomeFragment
import com.bawei.module_live.LiveFragment
import com.bawei.module_live.player.ExoPlayerManager
import com.bawei.module_mine.MineFragment
import com.bawei.module_open.OpenFragment
import com.bawei.module_video.ui.VideoFragment
import com.hyphenate.EMCallBack
import com.hyphenate.chat.EMClient
import com.tencent.mmkv.MMKV

@Route(path = "/module_main/MainActivity")
class MainActivity : AppCompatActivity() {
    private lateinit var viewPager: ViewPager2
    private lateinit var adapter: ViewPagerAdapter
    private var totalAmount = 0.00
    private var hasAdded = false
    private var progressAnimator: ValueAnimator? = null
    private var exoPlayerManager: ExoPlayerManager? = null

    // 新增：持有MineFragment实例
    private val mineFragment = MineFragment()

    // 底部导航栏图标数组
    private val navIcons = arrayOf(
        R.id.icon_home,
        R.id.icon_theater,
        R.id.nav_add,
        R.id.icon_live,
        R.id.icon_profile
    )
    private val navTexts = arrayOf(
        R.id.text_home,
        R.id.text_theater,
        R.id.text_add,
        R.id.text_live,
        R.id.text_profile
    )

    // 未选中和选中的颜色
    private val unselectedColor = Color.parseColor("#333333")
    private val selectedColor = Color.parseColor("#FF0000") // 红色

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        exoPlayerManager = ExoPlayerManager(this)
        ActivityCompat.requestPermissions(
            this,
            arrayOf(Manifest.permission.READ_PHONE_STATE),
            0
        )
        // 初始化ViewPager2
        viewPager = findViewById(R.id.view_pager)
        adapter = ViewPagerAdapter(this, mineFragment)
        viewPager.adapter = adapter

        // 设置ViewPager2的滑动冲突处理
        setupViewPagerScrollConflict()
        viewPager.isUserInputEnabled = false
        // 设置页面切换监听
        viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                updateBottomNavSelection(position)
                // 红包只在首页和放映厅显示
                val redPacketContainer =
                    findViewById<android.widget.FrameLayout>(R.id.red_packet_container)
                if (position == 0 || position == 1) {
                    redPacketContainer.visibility = View.VISIBLE
                } else {
                    redPacketContainer.visibility = View.GONE
                }
                if (position == 4) { // MineFragment
                    progressAnimator?.cancel()
                    // 同步金币金额
                    mineFragment.updateCoin(totalAmount)
                } else {
                    if (progressAnimator?.isRunning != true) {
                        progressAnimator?.start()
                    }
                }
            }
        })

        // 设置底部导航点击事件
        findViewById<LinearLayout>(R.id.nav_home).setOnClickListener {
            viewPager.currentItem = 0
        }

        findViewById<LinearLayout>(R.id.nav_theater).setOnClickListener {
            viewPager.currentItem = 1
        }

        findViewById<ImageView>(R.id.nav_add).setOnClickListener {
//            // 处理加号按钮点击事件
//            ARouter.getInstance().build("/open/OpenActivity").navigation()
            viewPager.currentItem = 2
        }

        findViewById<LinearLayout>(R.id.nav_live).setOnClickListener {
            viewPager.currentItem = 3
        }

        findViewById<LinearLayout>(R.id.nav_profile).setOnClickListener {
            viewPager.currentItem = 4
        }


        // 初始化选中第一个页面
        updateBottomNavSelection(0)

        // 红包动画逻辑（FrameLayout+inflate方式）
        val container = findViewById<android.widget.FrameLayout>(R.id.red_packet_container)
        val rewardView = layoutInflater.inflate(
            com.bawei.module_home.R.layout.layout_red_packet_reward,
            container,
            false
        )
        container.addView(rewardView)
        val progressCircle =
            rewardView.findViewById<com.bawei.module_home.widget.RedPacketProgressView>(com.bawei.module_home.R.id.progressCircle)
        val ivRedPacket = rewardView.findViewById<ImageView>(com.bawei.module_home.R.id.ivRedPacket)
        val tvAddAmount = rewardView.findViewById<TextView>(com.bawei.module_home.R.id.tvAddAmount)
        val tvTotalAmount =
            rewardView.findViewById<TextView>(com.bawei.module_home.R.id.tvTotalAmount)

        progressAnimator = ValueAnimator.ofFloat(0f, 1f)
        progressAnimator?.duration = 2000
        progressAnimator?.repeatCount = ValueAnimator.INFINITE
        progressAnimator?.interpolator = LinearInterpolator()
        progressAnimator?.addUpdateListener { animation ->
            val value = animation.animatedValue as Float
            progressCircle.setProgress(value)
            // 实时显示累计金额
            tvTotalAmount.text = "累计" + String.format("%.2f", totalAmount) + "元"
            // 只在接近1时触发动画
            if (value >= 0.99f && !hasAdded) {
                hasAdded = true
                tvAddAmount.visibility = View.VISIBLE
                tvAddAmount.text = "+0.01元"
                tvAddAmount.scaleX = 1.2f
                tvAddAmount.scaleY = 1.2f
                tvAddAmount.alpha = 1f
                tvAddAmount.animate().scaleX(1f).scaleY(1f).alpha(0.2f).setDuration(800)
                    .withEndAction {
                        tvAddAmount.visibility = View.GONE
                    }.start()
            }
        }
        progressAnimator?.addListener(object : android.animation.Animator.AnimatorListener {
            override fun onAnimationRepeat(animation: android.animation.Animator) {
                totalAmount += 0.01
                hasAdded = false
            }

            override fun onAnimationStart(animation: android.animation.Animator) {}
            override fun onAnimationEnd(animation: android.animation.Animator) {}
            override fun onAnimationCancel(animation: android.animation.Animator) {}
        })
        progressAnimator?.start()
        //环信登录
        val account = MMKV.defaultMMKV().decodeString("account")
        val password = MMKV.defaultMMKV().decodeString("password")
        if (account==null){

        }else{
            EMClient.getInstance().login(account, password, object : EMCallBack {
                // 登录成功回调
                override fun onSuccess() {
                }

                // 登录失败回调，包含错误信息
                override fun onError(code: Int, error: String) {
                }
            })
        }



    }

    /**
     * 更新底部导航栏选中状态
     */
    private fun updateBottomNavSelection(position: Int) {
        // 重置所有图标和文字颜色
        for (i in navIcons.indices) {
            // 重置图标颜色
            findViewById<ImageView>(navIcons[i]).setColorFilter(unselectedColor)
            if (i == 2) {
                findViewById<ImageView>(navIcons[i]).setColorFilter(selectedColor)
            }
            // 重置文字颜色
            findViewById<TextView>(navTexts[i]).setTextColor(unselectedColor)
        }

        // 设置当前选中项的颜色
        if (position < navIcons.size) {
            // 设置选中图标颜色
            findViewById<ImageView>(navIcons[position]).setColorFilter(selectedColor)
            // 设置选中文字颜色
            findViewById<TextView>(navTexts[position]).setTextColor(selectedColor)
        }
    }

    /**
     * 设置ViewPager2的滑动冲突处理
     */
    private fun setupViewPagerScrollConflict() {
        // 由于在RecyclerView层面已经处理了滑动冲突，这里只需要简单的处理
        // 或者可以完全移除这个方法调用
    }

    /**
     * 设置ViewPager2滑动是否启用
     * 这个方法会被MineFragment通过反射调用
     */
    fun setViewPagerScrollEnabled(enabled: Boolean) {
        viewPager.setUserInputEnabled(enabled)
    }

    override fun onDestroy() {
        exoPlayerManager?.release()
        super.onDestroy()
        progressAnimator?.cancel()
    }
}

class ViewPagerAdapter(fragmentActivity: FragmentActivity, private val mineFragment: MineFragment) :
    FragmentStateAdapter(fragmentActivity) {

    override fun getItemCount(): Int = 5

    override fun createFragment(position: Int): Fragment {
        return when (position) {
            0 -> HomeFragment()
            1 -> VideoFragment()
            2 -> OpenFragment()
            3 -> LiveFragment()
            4 -> mineFragment
            else -> throw IllegalArgumentException("Invalid position $position")
        }
    }
}
